package com.ithinkstudio.jeez.dao.impl;

import com.ithinkstudio.jeez.dao.IUserRepository;
import com.ithinkstudio.jeez.entity.User;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.io.Serializable;
import java.util.List;

/**
 * @program: jeez-springboot-bucket
 * @description: 用户DAO hibernate 实现
 * @author: fengzp
 * @create: 2020/04/15
 */
@Repository
public class UserRepository implements IUserRepository {

    @PersistenceContext
    private EntityManager entityManager;

    /**
     * 添加
     *
     * @param model
     */
    @Override
    public void insert(User model) {
        entityManager.persist(model);
    }

    /**
     * 修改
     *
     * @param model
     */
    @Override
    public void update(User model) {
        entityManager.persist(model);
    }

    /**
     * 删除
     *
     * @param model
     */
    @Override
    public void delete(User model) {
        entityManager.remove(model);
    }

    /**
     * 删除
     *
     * @param key
     */
    @Override
    public void delete(Serializable key) {
        User user = entityManager.find(User.class, key);
        if(null != user) {
            entityManager.remove(user);
        }
    }

    /**
     * 根据ID查询
     *
     * @param key
     * @return
     */
    @Override
    public User findById(Serializable key) {
        return entityManager.find(User.class, key);
    }

    /**
     * 根据hql查询集合
     *
     * @param hql
     * @param args
     * @return
     */
    @Override
    public List<User> list(String hql, Object[] args) {
        Query query = entityManager.createQuery(hql);
        if (null != args) {
            for(int i = 0; i < args.length; i++) {
                query.setParameter(i, args[i]);
            }
        }
        return query.getResultList();
    }
}
